package ran.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ran.constants.RedisCacheConstants;
import ran.friend.domain.user.entity.User;
import ran.friend.domain.user.vo.UserVO;
import ran.friend.mapper.user.UserMapper;
import ran.redis.service.RedisService;

import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-11-18
 * Time: 10:46
 */
@Component
public class UserRedisCacheManager {
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserMapper userMapper;


    // 获取详情信息的方法
    public UserVO getUserDetail(Long userId) {
        // 获取key
        String userKey = getUserKey(userId);
        UserVO userVO = redisService.getCacheObject(userKey, UserVO.class);
        if (userVO != null) {
            // 延长时间 10min
            redisService.expire(userKey, RedisCacheConstants.USER_EXP, TimeUnit.MINUTES);
            // 返回数据
            return userVO;
        }
        // 去MySQL查询
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .select(User::getUserId,
                                User::getNickName,
                                User::getHeadImage,
                                User::getSex,
                                User::getEmail,
                                User::getPhone,
                                User::getWechat,
                                User::getIntroduce,
                                User::getSchoolName,
                                User::getMajorName)
                        .eq(User::getUserId, userId));
        if (user == null) {
            return null;
        }
        // 刷新缓存
        refreshCache(user);
        // 返回
        UserVO newUserVO = new UserVO();
        BeanUtil.copyProperties(user, newUserVO);
        return newUserVO;
    }

    public void refreshCache(User user) {
        String userKey = getUserKey(user.getUserId());
        redisService.setCacheObject(userKey,user, RedisCacheConstants.USER_EXP,TimeUnit.MINUTES);
    }

    private String getUserKey(Long userId) {
        return RedisCacheConstants.USER_DETAIL + userId;
    }

}
